package com.zzyl.framework.interceptor;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zbr
 * @version 1.0
 * @since 2025/3/5 12:27
 */
@Component
@Slf4j
public class MemberInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.warn("MemberInterceptor拦截请求");
        // 非controller的请求之间放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // 1.获取header中的token
        String token = request.getHeader("authorization");
        // 2.token不存在则，响应401
        if (StrUtil.isBlank(token)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new BaseException("认证失败");
            // return false;
        }
        // 3.解析token，解析失败，响应401
        Claims claims = null;
        try {
            claims = tokenService.parseToken(token);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new BaseException("认证失败");
        }
        // 4.获取解析数据，数据为空，响应401
        Object userid = claims.get("id");
        if (ObjUtil.isNull(userid)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new BaseException("认证失败");
        }
        // 5.存储数据到ThreadLocal中
        UserThreadLocal.set(Long.valueOf(userid.toString()));
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 删除ThreadLocal中的数据
        log.warn("删除ThreadLocal中的数据");
        UserThreadLocal.remove();
    }
}
